package com.aiatomic.couting.scan;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Permissions;
import java.util.Calendar;

import com.aiatomic.couting.ICodeMsg;
import com.aiatomic.couting.IConstant;
import com.aiatomic.couting.PayActivity;
import com.aiatomic.couting.R;
import com.aiatomic.couting.ScanActivity;
import com.aiatomic.couting.SettingActivity;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.widgets.TaggableImageView.TAG_STAGE;

import android.Manifest;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

public class FragmentScanEnd extends Fragment {
    private View view;
    private ScanActivity activity;
    private int WRITE_FILE = 990;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_scan_end, container, false);
        view.findViewById(R.id.tagsToolBar).setVisibility(View.VISIBLE);
        activity = (ScanActivity) getActivity();
        view.findViewById(R.id.tagsToolBar).setVisibility(View.VISIBLE);
        view.findViewById(R.id.txtTagTools).setSelected(true);
        view.findViewById(R.id.toggleNumbersLayout).setSelected(false);
        ((TextView) view.findViewById(R.id.txtToggleNumbers)).setText(R.string.hide);
        bindEvent();
        return view;
    }

    // 保存到sdcard
    public void savePic(Bitmap b, int count, long time, String childDir) {
        SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(activity);

        FileOutputStream fos = null;
        try {
            Calendar now = Calendar.getInstance();
            String storePath = Environment.getExternalStorageDirectory() + File.separator + getString(R.string.app_name)
                    + File.separator + share.getString(IConstant.DEVICE_FOLDER_NAME, SystemUtil.getSystemModel());
            String folderStruct = share.getString(IConstant.FOLDER_STRUCTURE2, "Day");
            if (folderStruct.equals("Day")) {
                storePath += File.separator + String.valueOf(now.get(Calendar.YEAR)) + File.separator
                        + String.valueOf(now.get(Calendar.MONTH) + 1) + File.separator
                        + String.valueOf(now.get(Calendar.DAY_OF_MONTH)) + File.separator + childDir;
            }
            if (folderStruct.equals("Month")) {
                storePath += File.separator + String.valueOf(now.get(Calendar.YEAR)) + File.separator
                        + String.valueOf(now.get(Calendar.MONTH) + 1) + File.separator + childDir;
            }
            if (folderStruct.equals("Year")) {
                storePath += File.separator + String.valueOf(now.get(Calendar.YEAR)) + File.separator + childDir;
            }
            if (folderStruct.equals("Root")) {
                storePath += File.separator + childDir;
            }
            File dir = new File(storePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File f = new File(dir, String.valueOf(time) + ".jpg");
            if (f.exists()) {
                f.delete();
            }

            fos = new FileOutputStream(f);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            }
            if (share.getBoolean(IConstant.SAVE_SHOW_NUMBERS, Boolean.TRUE)) {
                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                exif.setAttribute("识别数量", String.valueOf(count));
                exif.saveAttributes();
            }
            Toast toast = Toast.makeText(activity, "保存至:" + f.getAbsolutePath(), Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toast.show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void save() {
        Bitmap image = (Bitmap) activity.scanImg.getScanImage().get("result");
        Bitmap src = (Bitmap) activity.scanImg.getScanImage().get("apply");
        int count = (int) activity.scanImg.getScanImage().get("count");
        long time = (long) activity.scanImg.getScanImage().get("time");
        savePic(image, count, time, "结果");
        SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(activity);
        if (share.getBoolean(IConstant.COPY_ORIG_IMAGE, Boolean.TRUE)) {
            savePic(src, count, time, "原图");
        }
    }

    private void bindEvent() {
        view.findViewById(R.id.saveOptionsToolLayout).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, SettingActivity.class);
                activity.startActivity(intent);
            }
        });
        view.findViewById(R.id.txtSaveTools).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    save();
                } else {
                	ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_FILE);
                }
            }
        });
        View moreBottom = view.findViewById(R.id.moreBottomId);
        moreBottom.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.dl.openDrawer(activity.lv);
            }
        });
        view.findViewById(R.id.txtTagTools).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (view.findViewById(R.id.tagsToolBar).getVisibility() == View.GONE) {
                    view.findViewById(R.id.tagsToolBar).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.txtTagTools).setSelected(true);
                } else {
                    view.findViewById(R.id.tagsToolBar).setVisibility(View.GONE);
                    view.findViewById(R.id.txtTagTools).setSelected(false);
                }
            }
        });

        view.findViewById(R.id.toggleNumbersLayout).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (view.findViewById(R.id.toggleNumbersLayout).isSelected()) {
                    view.findViewById(R.id.toggleNumbersLayout).setSelected(false);
                    ((TextView) view.findViewById(R.id.txtToggleNumbers)).setText(R.string.hide);
                    activity.scanImg.show_num = true;
                    activity.scanImg.invalidate();

                } else {
                    view.findViewById(R.id.toggleNumbersLayout).setSelected(true);
                    ((TextView) view.findViewById(R.id.txtToggleNumbers)).setText(R.string.show);
                    activity.scanImg.show_num = false;
                    activity.scanImg.invalidate();
                }
            }
        });

        view.findViewById(R.id.btnRefineLessTags).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                int min = 0, max = 0;
                for (ScanDrawable scan : activity.scanImg.drawables) {
                    if (scan.sensitive > max) {
                        max = scan.sensitive;
                    }
                    if (scan.sensitive < min) {
                        min = scan.sensitive;
                    }
                }
                if (activity.scanImg.sensitive_min < max) {
                    activity.scanImg.sensitive_min++;
                    activity.scanImg.invalidate();
                    activity.scanImg.reCount();
                }
            }
        });
        view.findViewById(R.id.btnRefinePLus).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                int min = 0, max = 0;
                for (ScanDrawable scan : activity.scanImg.drawables) {
                    if (scan.sensitive > max) {
                        max = scan.sensitive;
                    }
                    if (scan.sensitive < min) {
                        min = scan.sensitive;
                    }
                }
                if (activity.scanImg.sensitive_min > min) {
                    activity.scanImg.sensitive_min--;
                    activity.scanImg.invalidate();
                    activity.scanImg.reCount();
                }
            }
        });

        view.findViewById(R.id.btnSmallerTags).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (activity.scanImg.tag_size_scale > 0.7f) {
                    activity.scanImg.tag_size_scale -= 0.1f;
                    activity.scanImg.invalidate();

                }
            }
        });

        view.findViewById(R.id.btnLargerTags).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (activity.scanImg.tag_size_scale < 1.2f) {
                    activity.scanImg.tag_size_scale += 0.1f;
                    activity.scanImg.invalidate();
                }
            }
        });

        view.findViewById(R.id.txtAddTags).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.isSelected()) {
                    v.setSelected(false);
                    activity.scanImg.tag_state = TAG_STAGE.NORMAL;

                } else {
                    activity.scanImg.tag_state = TAG_STAGE.ADD;
                    v.setSelected(true);
                    if (view.findViewById(R.id.txtDeleteTags).isSelected()) {
                        view.findViewById(R.id.txtDeleteTags).setSelected(false);
                    }
                }
            }
        });

        view.findViewById(R.id.txtDeleteTags).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.isSelected()) {
                    v.setSelected(false);
                    activity.scanImg.tag_state = TAG_STAGE.NORMAL;
                } else {
                    v.setSelected(true);
                    activity.scanImg.tag_state = TAG_STAGE.DEL;
                    if (view.findViewById(R.id.txtAddTags).isSelected()) {
                        view.findViewById(R.id.txtAddTags).setSelected(false);
                    }
                }
            }
        });
    }
}
